package com.cheng.example.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
 * 一、用于解决多线程安全问题的方式：
 * synchronized:隐式锁
 * 1、同步代码块
 * 2、同步方法
 * jdk 1.5后
 * 3、同步锁 Lock
 * 注意：是一个显式锁，通过lock()方式上锁，必须通过unlock()方法释放锁
 */
public class TestLock1 {
    public static void main(String[] args) {

        Ticket1 ticket1 = new Ticket1();

        new Thread(() -> {
            for (int i = 0; i <3 ; i++) {
                ticket1.f1();
            }

        }).start();

        new Thread(() -> {
            ticket1.f2();
        }).start();

    }
}

class Ticket1 {
    private int tick = 100;
    private Lock lock = new ReentrantLock();

    Condition condition2 = lock.newCondition();


    public void f1() {
        lock.lock();
        try {
            Thread.sleep(2000);
            System.out.println("f1");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        lock.unlock();
    }

    public void f2() {
        lock.lock();
        try {
            condition2.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("f2");
        lock.unlock();
        System.out.println();
    }

}
